package com.cino.users.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cino.basic.base.exception.BusinessException;
import com.cino.basic.constant.WxConstants;
import com.cino.basic.interceptor.LoginInterceptor;
import com.cino.basic.jwt.JwtUtils;
import com.cino.basic.jwt.LoginData;
import com.cino.basic.jwt.RsaUtils;
import com.cino.basic.util.AjaxResult;
import com.cino.basic.util.HttpUtil;
import com.cino.basic.util.Md5Utils;
import com.cino.basic.util.StrUtils;
import com.cino.system.domain.Menu;
import com.cino.users.domain.Logininfo;
import com.cino.basic.base.service.impl.BaseServiceImpl;
import com.cino.users.domain.User;
import com.cino.users.domain.Wxuser;
import com.cino.users.dto.AccountDto;
import com.cino.users.mapper.LogininfoMapper;
import com.cino.users.mapper.UserMapper;
import com.cino.users.mapper.WxuserMapper;
import com.cino.users.service.LogininfoService;
import jdk.nashorn.internal.ir.ReturnNode;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.message.ReusableMessage;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import javax.swing.*;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements LogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String,Object> loadAccount(AccountDto accountDto) {
        //1.校验空值
        if(StringUtils.isEmpty(accountDto.getAccount()) || StringUtils.isEmpty(accountDto.getCheckPass())){
            throw new BusinessException("信息不能为空！");
        }
        //2.校验账号
        Logininfo logininfo = logininfoMapper.loadByAccount(accountDto);
        if(logininfo==null){
            throw new BusinessException("账号有误！");
        }
        //3.校验密码
        String salt = logininfo.getSalt();
        String inputMd5Pwd = Md5Utils.encrypByMd5(accountDto.getCheckPass()+salt);
        if(!inputMd5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误");
        }
        //4.校验是否禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该用户已被禁用，请联系管理员");
        }
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        return map;
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求:需要什么code，appid，secret?返回什么?token，openid
        //1.准备第二个请求的地址
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID).replace("SECRET",WxConstants.SECRET).
                replace("CODE",map.get("code"));//code是扫码人的code
        //2.使用HttpUtl发送微信登录请求:第二个请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastJson将json格式的字符串转成json对象:为了获取token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //4.通过openid查t wxuser表
        Wxuser wxuser =wxuserMapper.LoadByOpenid(openid);
        //4.1.查到了 - 以前扫过码 - 免密登录:返回true，token和logininfo对象
        if(wxuser!=null){//绑定过
            User user = userMapper.loadById(wxuser.getUserId());
            if(user!=null){
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                //免密登录
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                AjaxResult ajaxResult = new AjaxResult();
                return ajaxResult.setObj(resultMap);
            }
        }
        //4.2.没有查询到 -第一次扫码 _把token和openid响应给前端 - 到绑定页面进行绑定
        AjaxResult ajaxResult = new AjaxResult();
        return  ajaxResult.setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空！");
        }
        //2.校验-手机验证码:是否过期(redis中看是否有)，是否正确【业务键：电话号码 - 手机验证码：时间戳】
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj==null){
            throw new BusinessException("验证码过期");
        }
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码不正确");
        }
        //3.准备第三个请求(准备网站)
       String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN",accessToken).
                replace("OPENID",openId);
        //4.使用HttpUtl发送微信绑定请求- 获取微信用户信息:返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr-将json0bj中的数据转换WxUser对象
        Wxuser wxuser = jsonObj2Wxuser(jsonStr);
        //6.创建User对象和Logininfo对象【phone】-难度
        User user = userMapper.loadByPhone(phone);

        if(user==null){
            user = phone2User(phone);
            Logininfo newLogininfo =user2Logininfo(user);
            logininfoMapper.save(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.save(user);
        }
        wxuser.setUserId(user.getId());
        //7.添加数据库:Logininfo对象 - User对象 - WxUser对象
        wxuserMapper.save(wxuser);

        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setObj(resultMap);
        return ajaxResult;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(salt + pwd);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonObj2Wxuser(String jsonStr) {

        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObj.getString("openid"));
        wxuser.setNickname(jsonObj.getString("nickname"));
        wxuser.setHeadimgurl(jsonObj.getString("headimgurl"));
        wxuser.setUnionid(jsonObj.getString("unionid"));
        return wxuser;
    }

    //jwt加密方法
    public Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        HashMap<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        //设置logininfo
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        //设置管理员信息和菜单信息  permissions， Menus
        if(logininfo.getType() == 0){
          List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
          map.put("permissions",permissions);
          loginData.setPermissions(permissions);
          //设置 Menus
          List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
          map.put("menus",menus);
          loginData.setMenus(menus);
        }
        try {
            //设置JwtToken - 加密 - loginData
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  map;
    }

}
